package com.hxgis.statisticanalysis.common.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hxgis.statisticanalysis.common.config.ResponseData;
import com.hxgis.statisticanalysis.common.config.ResponseFormat;
import com.hxgis.statisticanalysis.utils.DateUtil;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(hidden = true)
@Controller
public class BaseController {
    protected static final int DEFAULT_RANGE_DATE = 1;//默认查询范围，1天

    private static ObjectMapper mapper = new ObjectMapper();

    private static final String encodings[] = new String[]{
            "ISO-8859-1",
            "GB2312",
            "GBK",
            "GB18030",
            "Big5",
            "Unicode",
            "ASCII"
    };

    private static final String default_encoding = "utf-8";

    private static final Map<String, String> image_type = new HashMap<String, String>() {
        {
            put("png", "image/png");
            put("jpeg", "image/jpeg");
            put("jpg", "image/jpeg");
            put("gif", "image/gif");
        }
    };

    //do something
    public void baseIndex(HttpServletRequest request,
                          HttpServletResponse response, Model model) {
        HttpSession session = request.getSession(true);
    }

    public static JsonNode getJsonFromFile(File file) {
        if (file.exists()) {
            try {
                return mapper.readTree(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * 返回状态码对应的msg数据
     *
     * @param code 状态码
     * @return
     */
    public ResponseData<Object> render(Integer code) {
        return ResponseFormat.parse(code);
    }

    /**
     * 返回ResponseEntity，code为200
     *
     * @param data 需要返回的数据
     * @return
     */
    public <T> ResponseData<T> render(T data) {
        return ResponseFormat.parse(data);
    }

    /**
     * 返回ResponseEntity，code为200
     *
     * @param data 需要返回的数据
     * @return
     */
    public <T> ResponseData<List<T>> render(List<T> data) {
        return ResponseFormat.parse(data);
    }

    /**
     * 返回ResponseEntity，code为200
     *
     * @param data      数据主体
     * @param startTime 数据开始时间
     * @param endTime   数据结束时间
     * @param <T>       数据类型
     * @return
     */
    public <T> ResponseData<List<T>> render(List<T> data, Long startTime, Long endTime) {
        return ResponseFormat.parse(data, startTime, endTime);
    }

    /**
     * 返回ResponseEntity，code为200
     *
     * @param data 数据主体
     * @param time 数据时间
     * @param <T>  数据类型
     * @return
     */
    public <T> ResponseData<List<T>> render(List<T> data, Long time) {
        return ResponseFormat.parse(data, time);
    }

    /**
     * 返回ResponseEntity，code为200
     *
     * @param data 数据主体
     * @param time 数据时间
     * @param <T>  数据类型
     * @return
     */
    public <T> ResponseData<T> render(T data, Long time) {
        return ResponseFormat.parse(data, time);
    }

    /**
     * 返回ResponseEntity，code为200
     *
     * @param data      数据主体
     * @param startTime
     * @param endTime
     * @param <T>       数据类型
     * @return
     */
    public <T> ResponseData<T> render(T data, Long startTime, Long endTime) {
        return ResponseFormat.parse(data, startTime, endTime);
    }

    /**
     * 转换map为java bean
     *
     * @param map       数据
     * @param beanClass class
     * @return object
     * @throws Exception 异常
     */
    /*public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
        if (map == null) {
            return null;
        }

        DateTimeConverter dtConverter = new DateTimeConverter();
        ConvertUtilsBean convertUtilsBean = new ConvertUtilsBean();
        convertUtilsBean.deregister(Date.class);
        convertUtilsBean.register(dtConverter, Date.class);
        BeanUtilsBean beanUtilsBean = new BeanUtilsBean(convertUtilsBean,
                new PropertyUtilsBean());
        Object obj = beanClass.newInstance();
        beanUtilsBean.populate(obj, map);
        return obj;
    }*/

    /**
     * 将其它编码格式的中文转换为utf-8编码
     *
     * @param text string
     * @return string
     */
    public static String getEncodingString(String text) {
        if (text != null) {
            try {
                String textEncoding = default_encoding;
                for (String encoding : encodings) {
                    if (text.equals(new String(text.getBytes(encoding), encoding))) {
                        textEncoding = encoding;
                        break;
                    }
                }
                return new String(text.getBytes(textEncoding), default_encoding);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return text;
    }

    /**
     * 自定义错误信息
     *
     * @param msg 错误信息
     * @return
     */
    public ResponseData<Object> render(String msg) {
        return ResponseFormat.parse(msg);
    }

    public static void setFileDownloadHeader(HttpServletResponse response, String fileName) {
        try {
            //中文文件名支持
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static void writeFile(HttpServletResponse response, InputStream inputStream, String contentType) {
        try {
            int available = inputStream.available();
            byte[] data = new byte[available];
            inputStream.read(data);
            inputStream.close();
            //写图片
            response.setContentType(contentType);
            response.setCharacterEncoding(default_encoding);
            OutputStream stream = new BufferedOutputStream(response.getOutputStream());
            stream.write(data);
            stream.flush();
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void writeImage(HttpServletResponse response, String fileName, InputStream inputStream) {
        if (inputStream != null) {
            String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
            String contentType = image_type.get(prefix);
            writeFile(response, inputStream, contentType);
        }
    }

    public static String getBase64ImgHeader(String fileName) {
        String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
        String contentType = image_type.get(prefix);
        return "data:" + contentType + ";base64,";
    }

    public static void writeMediaFile(File file) {

    }

    /**
     * 将固定格式（yyyy-MM-dd HH:mm:ss）的时间字符串转为时间戳
     * TODO 后续支持不同格式时间字符串
     *
     * @param timeStr 固定格式的时间字符串
     * @return 时间戳
     */
    public Long getTime(String timeStr) {
        Long timestamp = StringUtils.isNotEmpty(timeStr) ? DateUtil.str2DateByFormat(timeStr, DateUtil.DATEFORMART_DEFAULT).getTime() : null;
        return timestamp;
    }
}